package servlet;

import service.UserService;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;

/**
 * 注册服务
 */
@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
    private UserService userService = new UserService();
    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        //设置编码
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        PrintWriter out = response.getWriter();

        try{
            //获取参数
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            String email = request.getParameter("email");

            System.out.println("接收到注册请求: username=" + username +
                               ", password=" + password + ", email=" + email);

            //参数校验
            if(username == null || username.trim().isEmpty() ||
               password == null || password.trim().isEmpty() ||
               email == null || email.trim().isEmpty()) {
                out.println("参数错误");
                return;
            }
            boolean isRegistered = userService.register(username, password, email);
            if(isRegistered) {
                out.println("注册成功");
            } else {
                out.println("注册失败");
            }
        }
        catch(Exception e) {
            e.printStackTrace();
            out.println("注册失败");
        }
    }
}
